//
//  BBHomeViewController.swift
//  BBLinkiOSProject
//
//  Created by liuzhu on 2018/11/9.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import AFNetworking
import SVProgressHUD
import UIKit
let BBHomeActivityIdentifier = "BBHomeActivityIdentifier"
let BBHomeClockIdentifier = "BBHomeClockIdentifier"
class BBHomeViewController: BBBaseViewController {
    private lazy var currentDayId: String = {
        var str = String()
        let now = Date()
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy-MM-dd"
        str = dformatter.string(from: now as Date)
        return str
    }()
    private var currentDateCom: DateComponents = Calendar.current.dateComponents([.year, .month, .day], from: Date())
    var activitys: [BBActivity]? {
        didSet {
            tableView.reloadData()
        }
    }

    var day: BBDay? {
        didSet {
            //tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // 1.如果没有登录, 就设置未登录界面的信息
        if !userLogin {
            visitorView?.setupVisitorInfo(animationType: 1, imageName: "Visitor_home_back", message: "View daily motion records!")
            return
        }
        setupNav()
        tableView.register(BBActivityCell.self, forCellReuseIdentifier: BBHomeActivityIdentifier)
        tableView.register(BBClockCell.self, forCellReuseIdentifier: BBHomeClockIdentifier)
        view.addSubview(tableView)
        view.addSubview(simulationBtn)
        view.addSubview(noDataLabel)
    }
    
    override func viewWillAppear(_ animated: Bool) {
         if userLogin {
            loadDay(dayId: currentDayId)
        }
    }

    private func setupNav() {
        // 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem(imageName: "navigation_me", target: self, action: #selector(leftItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem.creatBarButtonItem(imageName: "navigation_refresh", target: self, action: #selector(rightItemClick))
        // 标题按钮
        let titleBtn = TitleButton()
        titleBtn.setTitle("\(currentDayId as String) ", for: UIControl.State.normal)
        titleBtn.addTarget(self, action: #selector(titleClick), for: UIControl.Event.touchUpInside)
        navigationItem.titleView = titleBtn
    }

    private func loadDay(dayId: String) {
        SVProgressHUD.show()
        BBDay.loadData(dayId: dayId) { day, error in
            if day != nil {
                self.day = day
                self.loadActivity()
            } else {
                SVProgressHUD.dismiss()
                self.activitys?.removeAll()
            }
        }
    }

    private func loadActivity() {
        BBActivity.loadData(dayId: currentDayId) { activitys, _ in
            SVProgressHUD.dismiss()
            self.activitys = activitys
        }
    }

    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: UIScreen.main.bounds)
        tableView.rowHeight = 210
        //tableView.estimatedRowHeight = 210
        //tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        return tableView
    }()

    private lazy var simulationBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 120, width: 80, height: 30))
        btn.setTitle("Ride >>", for: UIControl.State.normal)
        btn.alpha = 0.7
        btn.backgroundColor = UIColor.darkGray
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)

        let maskPath = UIBezierPath(roundedRect: btn.bounds, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.topRight.rawValue | UIRectCorner.bottomRight.rawValue), cornerRadii: CGSize(width: 15, height: 15))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = btn.bounds
        maskLayer.path = maskPath.cgPath
        btn.layer.mask = maskLayer
//        btn.layer.cornerRadius = 5.0
        btn.layer.masksToBounds = false // 如果是true，阴影不显示
        btn.layer.shadowColor = UIColor.lightGray.cgColor
        btn.layer.shadowOpacity = 1.0
        btn.layer.shadowRadius = 5.0
        btn.layer.shadowOffset = CGSize(width: 0, height: 0)
        btn.addTarget(self, action: #selector(simulationIng), for: UIControl.Event.touchUpInside)
        return btn
    }()

    private lazy var noDataLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 50, y: UIScreen.main.bounds.size.height / 2, width: UIScreen.main.bounds.size.width - 100, height: 40))
        label.text = "There is no riding data today."
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byTruncatingTail
        label.textAlignment = NSTextAlignment.center
        label.textColor = UIColor.lightGray
        return label
    }()

    @objc private func simulationIng() {
        let vc = SimulationViewController(nibName: "SimulationViewController", bundle: nil)
        present(vc, animated: true, completion: nil)
    }

    @objc private func leftItemClick() {
        NSLog(#function)
        let sb = UIStoryboard(name: "BBMe", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        present(vc!, animated: true, completion: nil)
        // self.navigationController?.pushViewController(vc!, animated: true)
    }

    @objc private func rightItemClick() {
        NSLog(#function)
        loadDay(dayId: currentDayId)
    }

    @objc private func titleClick(btn: TitleButton) {
        NSLog(#function)
        //btn.isSelected = !btn.isSelected
        //弹出菜单
        let dataPicker = EWDatePickerViewController()
        self.definesPresentationContext = true
        /// 回调显示方法
        dataPicker.backDate = { [weak self] date in
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "YYYY-MM-dd"
            let dateString: String = dateFormatter.string(from: date)
            btn.setTitle(dateString, for: UIControl.State.normal)
            self?.currentDayId = dateString
            self!.loadDay(dayId: self!.currentDayId)
        }
        dataPicker.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
        dataPicker.picker.reloadAllComponents()
        /// 弹出时日期滚动到当前日期效果
        self.present(dataPicker, animated: true) {
            dataPicker.picker.selectRow(0, inComponent: 0, animated: true)
            dataPicker.picker.selectRow((self.currentDateCom.month!) - 1, inComponent: 1, animated:   true)
            dataPicker.picker.selectRow((self.currentDateCom.day!) - 1, inComponent: 2, animated: true)
        }
    }
}

extension BBHomeViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if day == nil || day?.isclocked == 0 {
            return activitys?.count ?? 0
        }
        return ((activitys?.count ?? 0) + 1)
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row >= (activitys?.count)! {
            let cell = tableView.dequeueReusableCell(withIdentifier: BBHomeClockIdentifier, for: indexPath) as! BBClockCell
            cell.shareBT.addTarget(self, action: #selector(share), for: UIControl.Event.touchUpInside)
            cell.day = day
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: BBHomeActivityIdentifier, for: indexPath) as! BBActivityCell
        let activity = activitys![indexPath.row]
        cell.activity = activity
        return cell
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footView = UIView()
        footView.backgroundColor = UIColor.clear
        let footerBT = UIButton(type: UIButton.ButtonType.custom)
        footerBT.frame = CGRect(x: 100, y: 10, width: UIScreen.main.bounds.size.width - 200, height: 50)
        footerBT.backgroundColor = UIColor(red: 249 / 255.0, green: 245 / 255.0, blue: 237 / 255.0, alpha: 1)
        footerBT.layer.cornerRadius = 10.0
        footerBT.layer.masksToBounds = false // 如果是true，阴影不显示
        footerBT.layer.shadowColor = UIColor.lightGray.cgColor
        footerBT.layer.shadowOpacity = 1.0
        footerBT.layer.shadowRadius = 5.0
        footerBT.layer.shadowOffset = CGSize(width: 0, height: 0)
        footerBT.setTitleColor(UIColor(red: 161 / 255.0, green: 161 / 255.0, blue: 161 / 255.0, alpha: 1), for: UIControl.State.normal)
        footerBT.setTitle("Click", for: UIControl.State.normal)
        footerBT.alpha = 0.8
        footerBT.addTarget(self, action: #selector(click), for: UIControl.Event.touchUpInside)
        footView.addSubview(footerBT)
        return footView
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if (activitys?.count) == nil {
            noDataLabel.isHidden = false
            return 0
        }
        if day == nil {
            noDataLabel.isHidden = false
            return 0
        }
        if activitys!.count <= 0 {
            noDataLabel.isHidden = false
            return 0
        }
        if day!.isclocked == 1 {
            noDataLabel.isHidden = true
            return 0
        }
        noDataLabel.isHidden = true
        return 70
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row >= (activitys?.count)! {
            return
        }
        let vc = BBActivityDetailViewController(nibName: "BBActivityDetailViewController", bundle: nil)
        let activity = activitys![indexPath.row]
        vc.activity = activity
        navigationController?.pushViewController(vc, animated: false)
    }

    @objc private func click() {
        let vc = BBClockViewController(nibName: "BBClockViewController", bundle: nil)
        if day != nil {
            vc.day = day
        } else {
            SVProgressHUD.showError(withStatus: "no data for clock")
        }
        navigationController?.pushViewController(vc, animated: false)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row >= (activitys?.count)! {
            return 460
        } else {
            return 210
        }
    }

    @objc private func share() {
        let AlertCon = UIAlertController(title: "Clock", message: "Do you want to send it to link?", preferredStyle: UIAlertController.Style.alert)
        let ActionSure = UIAlertAction(title: "Sure", style: UIAlertAction.Style.default) { _ in
            SVProgressHUD.show()
            let path = "link/send.do"
            let params = ["token": BBUser.loadUser()?.token, "userId": BBUser.loadUser()?.userId, "description": self.day?.clockDes, "linkType": "2", "linkImage": self.day?.clockImage, "usedTime": self.day?.totalTime, "times": self.day?.times, "mileage": self.day?.totalDistance] as [String: Any]
            let data = NSData()
            AFNetWorkManager.shareNetworkTools().post(path, parameters: params, constructingBodyWith: { fromData in
                fromData.appendPart(withFileData: data as Data, name: "upload_file", fileName: "png", mimeType: "application/octet-stream")
            }, progress: { _ in

            }, success: { _, _ in
                SVProgressHUD.dismiss()
                SVProgressHUD.showSuccess(withStatus: "Share it to link,Success!")
            }) { _, _ in
                SVProgressHUD.dismiss()
                SVProgressHUD.showSuccess(withStatus: "Share it to link,Failed!")
            }
        }
        let ActionCancel = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) { _ in
        }
        AlertCon.addAction(ActionSure)
        AlertCon.addAction(ActionCancel)
        present(AlertCon, animated: true, completion: nil)
    }
}
